package com.kaifamiao.context;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

@WebServlet( "/dispatcher/*" )
public class DispatcherServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void service( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        String uri = request.getRequestURI();
        logger.info( uri );

        String type = "path" ;
        int index = uri.lastIndexOf( "/" );
        if( index != -1 && index != uri.length() - 1 ) {
            type = uri.substring( index + 1 );
        }

        logger.info( type );

        ServletContext application = request.getServletContext();

        RequestDispatcher dispatcher ;

        switch ( type ) {
            case "name" :
                String name = "welcomeServlet" ;
                // 根据 servlet name 获取可以去往指定 servlet 的 RequestDispatcher
                dispatcher = application.getNamedDispatcher( name );
                break;
            case "path":
                String path = "/application/counter" ;
                // 注意这里的路径是当前应用内部另外一个资源的虚拟路径
                dispatcher = application.getRequestDispatcher( path );
                logger.info( "即将去往 " + path );
                break;
            default:
                // 通过 request.getContextPath() 获得当前 Web应用的路径
                response.sendRedirect( request.getContextPath()+ "/index.jsp" );
                return ;
        }

        dispatcher.forward( request , response );

    }

}
